package com.liy.framework.common.utils;

import java.lang.reflect.*;

public class ReflectUtil
{
    public static Object getFieldValue(final String fieldName, final Object obj) {
        return getFieldValue(fieldName, obj, null);
    }
    
    public static Object getFieldValue(final String fieldName, final Object obj, final Object defaultValue) {
        try {
            final Field field = getField(fieldName, obj.getClass());
            if (field != null) {
                Object value;
                if (!field.isAccessible()) {
                    field.setAccessible(true);
                    value = field.get(obj);
                    field.setAccessible(false);
                }
                else {
                    value = field.get(obj);
                }
                return value;
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return defaultValue;
    }
    
    public static Field getField(final String fieldName, Class<?> clazz) {
        Field field = null;
        while (clazz != Object.class) {
            try {
                field = clazz.getDeclaredField(fieldName);
                if (field != null) {
                    break;
                }
            }
            catch (Exception ex) {}
            clazz = clazz.getSuperclass();
        }
        return field;
    }
}
